package com.example.pei.ithinklearnt.present;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.model.AlumniCircleModelImp;
import com.example.pei.ithinklearnt.model.PraiseModel;
import com.example.pei.ithinklearnt.model.PraiseModelImp;
import com.example.pei.ithinklearnt.view.interfaces.PersonalDynamicsInterface;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                     佛祖保佑        永无BUG
 *            佛曰:
 *                   写字楼里写字间，写字间里程序员；
 *                   程序人员写程序，又拿程序换酒钱。
 *                   酒醒只在网上坐，酒醉还来网下眠；
 *                   酒醉酒醒日复日，网上网下年复年。
 *                   但愿老死电脑间，不愿鞠躬老板前；
 *                   奔驰宝马贵者趣，公交自行程序员。
 *                   别人笑我忒疯癫，我笑自己命太贱；
 *                   不见满街漂亮妹，哪个归得程序员？
*/

public class PersonalDynamicsPresentImp implements PersonalDynamicsPresent{

    private PersonalDynamicsInterface personalDynamicsInterface;
    private AlumniCircleModelImp alumniCircleModel;
    private PraiseModel praiseModel;

    private Date oldestDynamicDate;  //最老的动态时间
    private static final int STATE_REFRESH = 0;// 下拉刷新
    private static final int STATE_MORE = 1;// 加载更多

    private KProgressHUD hud; //等待进度条

    public PersonalDynamicsPresentImp(PersonalDynamicsInterface personalDynamicsInterface){
        this.personalDynamicsInterface=personalDynamicsInterface;
        this.alumniCircleModel=new AlumniCircleModelImp();
        this.praiseModel=new PraiseModelImp();
    }


    @Override
    public void refresh() {
//        personalDynamicsInterface.setLoadViewVisiable(true);
        queryData(STATE_REFRESH,10);

    }

    @Override
    public void loadmore() {
        queryData(STATE_MORE,10);
    }

    public void queryData(final int actionType, int limit) {
        if(AppApplication.getCurrentUser()==null){
            return;
        }
        BmobQuery<AlumniCircle> query = new BmobQuery<>();
        // 按时间降序查询
        query.order("-createdAt");
        query.addWhereEqualTo("sender", personalDynamicsInterface.getDisplayUser());
        query.include("sender");
        // 如果是加载更多
        if (actionType == STATE_MORE) {
            //只查询小于等于最后一个item发表时间的数据
            if(oldestDynamicDate!=null) {
                query.addWhereLessThan("createdAt", new BmobDate(oldestDynamicDate));
            }
        }
        // 设置每页数据个数
        query.setLimit(limit);
        // 查找数据
        query.findObjects(new FindListener<AlumniCircle>() {
            @Override
            public void done(List<AlumniCircle> Serverlist, BmobException e) {
                if(e==null){
                    //重新设置数据空时的view
                    personalDynamicsInterface.setEmptyView();
                    personalDynamicsInterface.setLoadViewVisiable(false);
                    if (Serverlist.size() > 0) {
                        if (actionType == STATE_REFRESH) {
                            // 当是下拉刷新操作时,清空adaper，重新添加数据
                            personalDynamicsInterface.getAdapter().clearDate();
                            //设置下拉刷新结束
                            personalDynamicsInterface.finishRefresh(true);
                        }else{
                            //设置上拉加载更多结束
                            personalDynamicsInterface.finishLoadMore(true);
                        }
                        // 将本次查询的数据添加到adapter中
                        for (AlumniCircle td : Serverlist) {
                            if(!alumniCircleModel.isDynamicShielded(td.getObjectId(), AppApplication.getCurrentUser().getUsername()))
                            {
                                //不是屏蔽的信息则可以进行添加
                                if(praiseModel.isDynamicPraiseed(td.getObjectId(),AppApplication.getCurrentUser().getUsername()))
                                {
                                    //被点赞的
                                    td.setIsPraise(1);
                                }else {
                                    td.setIsPraise(0);
                                }
                                personalDynamicsInterface.getAdapter().addDatetoFoot(td);
                            }
                        }

                        // 更新最老的数据时间// 处理时间查询
                        String lastTime = Serverlist.get(Serverlist.size() - 1).getCreatedAt();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            oldestDynamicDate = sdf.parse(lastTime);
                        } catch (ParseException ee) {
                            ee.printStackTrace();
                        }
                        if (actionType == STATE_REFRESH) {
                            personalDynamicsInterface.getAdapter().notifyDataSetChanged();     //刷新
                            //如果刷新完数量太少，那么自动加载更多(万一有傻逼屏蔽了所有最新的动态
                            if(personalDynamicsInterface.getAdapter().getmList().size()<=5){
                                queryData(STATE_MORE,10);
                            }
                        }else{
                            //同上
                            if(Serverlist.size()<=5){
                                queryData(STATE_MORE,10);
                            }
                        }
                    } else if (actionType == STATE_MORE) {
                       // Toast.makeText(personalDynamicsInterface.getActivityy(),"没有更多了哦 ￣ω￣= ",Toast.LENGTH_SHORT).show();
                        personalDynamicsInterface.finishLoadMore(true);
                    } else if (actionType == STATE_REFRESH) {
                        personalDynamicsInterface.getAdapter().clearDate();
                      //  Toast.makeText(personalDynamicsInterface.getActivityy(),"没有数据",Toast.LENGTH_SHORT).show();
                        personalDynamicsInterface.finishRefresh(true);
                    }
                }else{
                    //错误
                    if (actionType == STATE_MORE) {
                        personalDynamicsInterface.finishLoadMore(false);
                      //  Toast.makeText(personalDynamicsInterface.getActivityy(),"加载失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }else {
                        personalDynamicsInterface.finishRefresh(false);
                     //   Toast.makeText(personalDynamicsInterface.getActivityy(),"刷新失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }
                }
            }

        });
    }



    @Override
    public void praiseAlumniCircle(final int position) {
        //服务器上查看是否从未点赞状态变成改变状态
        praiseModel.praiseAlumniCircle(AppApplication.getCurrentUser().getUsername(), personalDynamicsInterface.getAdapter().getmList().get(position).getObjectId(),
                new PraiseModelImp.praiseAlumniCircle() {
                    @Override
                    public void becomePraised() {
                        //未点赞状态变成点赞状态
                        personalDynamicsInterface.getAdapter().getmList().get(position).setIsPraise(1);
                        personalDynamicsInterface.getAdapter().notifyItemChanged(position,1);
                    }
                });
        alumniCircleModel.addOneLike( personalDynamicsInterface.getAdapter().getmList().get(position).getObjectId());

        int count=personalDynamicsInterface.getAdapter().getmList().get(position).getPraiseNumber();
        count++;
        personalDynamicsInterface.getAdapter().getmList().get(position).setPraiseNumber(count);
        personalDynamicsInterface.getAdapter().notifyItemChanged(position,1);
    }

    @Override
    public void deleteAlumniCircle(int position,final deleteAlumniCircleListener listener) {
        hud = KProgressHUD.create(personalDynamicsInterface.getActivityy())
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("正在删除...")
                .setCornerRadius(10)
                .show();
        //删除某个动态及相关图片
        alumniCircleModel.deleteAlumniCircle( personalDynamicsInterface.getAdapter().getmList().get(position),
                personalDynamicsInterface.getAdapter().getmList().get(position).getphotos(),
                new AlumniCircleModelImp.deleteAlumniCircle() {
                    @Override
                    public void succeed() {
                        listener.succeed();
                        hud.dismiss();
                    }

                    @Override
                    public void failed() {
                        listener.failed();
                        hud.dismiss();
                    }
                });
    }

    @Override
    public void refreshOnlyOne(final int position) {
        //要刷新的objectId
        final String objectId=personalDynamicsInterface.getAdapter().getmList().get(position).getObjectId();
        final int isPraised=personalDynamicsInterface.getAdapter().getmList().get(position).getIsPraise();
        alumniCircleModel.findAlumniCircleByObjectId(objectId, new AlumniCircleModelImp.findAlumniCircle() {
            @Override
            public void success(AlumniCircle object) {
                //更新adapter的内容
                personalDynamicsInterface.getAdapter().getmList().set(position,object);
                personalDynamicsInterface.getAdapter().getmList().get(position).setIsPraise(isPraised);
                personalDynamicsInterface.getAdapter().getmList().get(position).setIsPraise(praiseModel.isDynamicPraiseed(objectId,AppApplication.getCurrentUser().getUsername())?1:0);
                //刷新
                personalDynamicsInterface.getAdapter().notifyItemChanged(position);
            }

            @Override
            public void failed(BmobException e) {

            }
        });
    }
}
